package com.yaoweigroup.community.ui.go;

import java.util.List;

import org.apache.http.entity.StringEntity;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMap.OnMapClickListener;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.AMap.InfoWindowAdapter;
import com.amap.api.maps2d.AMap.OnInfoWindowClickListener;
import com.amap.api.maps2d.AMap.OnMapLoadedListener;
import com.amap.api.maps2d.AMap.OnMarkerClickListener;
import com.amap.api.maps2d.AMap.OnMarkerDragListener;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.yaoweigroup.community.CApplication;
import com.yaoweigroup.community.R;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.enity.Evcard;
import com.yaoweigroup.community.util.DialogUtil;
import com.yaoweigroup.community.util.JsonUtil;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.UtilHttp;

/**
 * EVCARD
 * 
 * @author xi
 * 
 */
public class EvcardActivity extends Activity implements OnMarkerClickListener,
		OnInfoWindowClickListener, OnMarkerDragListener, OnMapLoadedListener,
		OnClickListener, InfoWindowAdapter, LocationSource,
		AMapLocationListener, OnMapClickListener {
	private RelativeLayout left_rl;
	private MapView mapView;
	public final int OBTAIN_SUCCESS = 0x2210;
	public final int OBTAIN_FAIL = OBTAIN_SUCCESS + 1;

	private List<Evcard> list;
	private ObjectMapper mapper;
	private MarkerOptions markerOption;
	private AMap aMap;

	private OnLocationChangedListener mListener;
	private LocationManagerProxy mAMapLocationManager;
	private Dialog dialog;
	private LinearLayout info_ll;
	private TextView name_tv;
	private TextView address_tv;
	private TextView detail_tv;
	private TextView des_tv;
	private Evcard currentCard;
	private boolean isMarkClick = false;
	private TextView service_tv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mapper = new ObjectMapper();
		setContentView(R.layout.activity_evcard);
		name_tv = (TextView) findViewById(R.id.name_tv);
		address_tv = (TextView) findViewById(R.id.address_tv);
		address_tv.setOnClickListener(this);
		detail_tv = (TextView) findViewById(R.id.detail_tv);
		des_tv = (TextView) findViewById(R.id.des_tv);

		info_ll = (LinearLayout) findViewById(R.id.info_ll);
		dialog = DialogUtil.createWaitDialog(this, "网点数据获取中..");
		mapView = (MapView) findViewById(R.id.map);
		service_tv = (TextView) findViewById(R.id.service_tv);
		service_tv.setOnClickListener(this);

		mapView.onCreate(savedInstanceState);// 此方法必须重写
		left_rl = (RelativeLayout) findViewById(R.id.left_rl);
		left_rl.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				finish();
			}
		});

		init();
		query();
	}

	/**
	 * 初始化AMap对象
	 */
	private void init() {

		if (aMap == null) {
			aMap = mapView.getMap();
			setUpMap();

			if (CApplication.latLng != null) {
				MyLocationStyle myLocationStyle = new MyLocationStyle();
				myLocationStyle.myLocationIcon(BitmapDescriptorFactory
						.fromResource(R.drawable.location_marker));// 设置小蓝点的图标
				myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
				myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
				// myLocationStyle.anchor(int,int)//设置小蓝点的锚点
				myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
				aMap.setMyLocationStyle(myLocationStyle);
				aMap.setLocationSource(this);// 设置定位监听
				aMap.setOnMapClickListener(this);
				aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
				aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
			}
		}

	}

	private void setUpMap() {
		aMap.setOnMarkerDragListener(this);// 设置marker可拖拽事件监听器
		aMap.setOnMapLoadedListener(this);// 设置amap加载成功事件监听器
		aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
		aMap.setOnInfoWindowClickListener(this);// 设置点击infoWindow事件监听器
		aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
		// addMarkersToMap();// 往地图上添加marker
	}

	private void query() {
		dialog.show();
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.evard, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							if (state == 200) {
								String data = obj.getString("data");
								list = mapper.readValue(data,
										new TypeReference<List<Evcard>>() {
										});
								handler.sendEmptyMessage(OBTAIN_SUCCESS);
							} else {
								handler.sendEmptyMessage(OBTAIN_FAIL);
							}
						} catch (Exception e) {
							handler.sendEmptyMessage(OBTAIN_FAIL);

						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(OBTAIN_FAIL);

					}

				});
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			dialog.dismiss();
			switch (msg.what) {
			case OBTAIN_FAIL:
				Toast.makeText(EvcardActivity.this, "获取失败!", 500).show();
				break;
			case OBTAIN_SUCCESS:
				if (aMap != null) {
					aMap.clear();
				}
				if (list != null) {
					LogUtil.d("wxf", "list=" + list.size());
					for (int i = 0; i < list.size(); i++) {
						Evcard card = list.get(i);
						Marker marker = aMap
								.addMarker(new MarkerOptions()
										.position(
												new LatLng(card.getLatitude(),
														card.getLongitude()))
										.title("网点名字：" + card.getShopName())
										.icon(BitmapDescriptorFactory
												.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
										.draggable(true));
						marker.setObject(card);
					}
				}
				break;
			}
		};
	};

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onResume() {
		super.onResume();
		mapView.onResume();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onPause() {
		super.onPause();
		mapView.onPause();
		deactivate();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mapView.onDestroy();
	}

	@Override
	public View getInfoContents(Marker arg0) {
		return null;
	}

	@Override
	public View getInfoWindow(Marker arg0) {
		return null;
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.address_tv:
			if (currentCard == null)
				return;
			Intent intent = new Intent(this,
					com.yaoweigroup.community.ui.bm.RouteActivity.class);
			intent.putExtra("lat", currentCard.getLatitude() + "");
			intent.putExtra("lng", currentCard.getLongitude() + "");
			startActivity(intent);
			break;
		case R.id.service_tv:
			info_ll.setVisibility(View.GONE);
			break;
		}
	}

	@Override
	public void onMapLoaded() {

	}

	@Override
	public void onMarkerDrag(Marker arg0) {

	}

	@Override
	public void onMarkerDragEnd(Marker arg0) {

	}

	@Override
	public void onMarkerDragStart(Marker arg0) {

	}

	@Override
	public void onInfoWindowClick(Marker arg0) {

	}

	@Override
	public boolean onMarkerClick(Marker marker) {
		info_ll.setVisibility(View.VISIBLE);
		isMarkClick = true;
		Evcard card = (Evcard) marker.getObject();
		currentCard = card;
		// info_ll.setVisibility(View.VISIBLE);
		name_tv.setText("网点名字: " + card.getShopName());
		address_tv.setText("网点地址: " + card.getAddress());
		detail_tv.setText("详情: " + "充电桩数:" + card.getAllowStackCnt() + " 可借车量:"
				+ card.getAllowVehicleCnt());
		des_tv.setText("描述: " + card.getShopDesc());
		return false;
	}

	@Override
	public void activate(OnLocationChangedListener listener) {
		mListener = listener;
		if (mAMapLocationManager == null) {
			mAMapLocationManager = LocationManagerProxy.getInstance(this);
			/*
			 * mAMapLocManager.setGpsEnable(false);
			 * 1.0.2版本新增方法，设置true表示混合定位中包含gps定位，false表示纯网络定位，默认是true Location
			 * API定位采用GPS和网络混合定位方式
			 * ，第一个参数是定位provider，第二个参数时间最短是2000毫秒，第三个参数距离间隔单位是米，第四个参数是定位监听者
			 */
			mAMapLocationManager.requestLocationUpdates(
					LocationProviderProxy.AMapNetwork, 2000, 10, this);
		}
	}

	@Override
	public void deactivate() {
		mListener = null;
		if (mAMapLocationManager != null) {
			mAMapLocationManager.removeUpdates(this);
			mAMapLocationManager.destory();
		}
		mAMapLocationManager = null;
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLocationChanged(AMapLocation aLocation) {
		if (mListener != null && aLocation != null) {
			mListener.onLocationChanged(aLocation);// 显示系统小蓝点
		}
	}

	@Override
	public void onMapClick(LatLng arg0) {
		//
		// if (info_ll.getVisibility() == View.VISIBLE && isMarkClick) {
		// info_ll.setVisibility(View.GONE);
		// } else {
		//
		// }

	}

}
